﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;

public partial class WebForm_CSharpCode_SelectControl : System.Web.UI.UserControl 
{
    private int FRowCount;
    private HiddenField FRowCountField=new  HiddenField();

    #region Page

        protected void Page_Init(object sender, EventArgs e)
        {
            FRowCountField.ID = "__RowCount";
            this.Controls.Add(FRowCountField);

            //取得上次記錄的資料列數 
            if (this.Request.Form[FRowCountField.UniqueID] == null)
            {
                FRowCount = 0;
            }
            else
            {
                FRowCount = Convert.ToInt16(this.Request.Form[FRowCountField.UniqueID]);
            }


            //判斷 __EVENTTARGET HiddenField 的值，來判斷是否為 Button Click 產生的 PostBack 動作
            if (this.Request.Form["__EVENTTARGET"] != null )
            {
                if (this.Request.Form["__EVENTTARGET"].StartsWith(btnAdd.UniqueID))
                { 
                    FRowCount = FRowCount + 1;            
                }
                else if (this.Request.Form["__EVENTTARGET"].StartsWith(btnOK.UniqueID) || this.Request.Form["__EVENTTARGET"].StartsWith(btnCancel.UniqueID))
                { 
                    FRowCount = 0;            
                }

            }

            CreateTable(FRowCount);
            //動態產生 Table。 


        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Page.Form.DefaultButton = btnQuery.UniqueID;

            FRowCountField.Value = FRowCount.ToString();

            if (!IsPostBack)
            {

                if (vSelectMode == EnumSelectMode.SingleSelect)
                {
                    GridView1.Columns[0].Visible = false;
                    btnOK.Visible = false;
                    btnCancel.Visible = false; 
                }

                lblTitle.Text = this.GetLocalResourceObject(vTagName +  "_Title").ToString(); 

            }

            ObjectDataSource1.SelectMethod = "BLL_SELECT_" + vTagName; //沒有ViewState
            ObjectDataSource1.FilterExpression = "1=1";

            //if (!IsPostBack)
            //{
            //    ObjectDataSource1.Select();//
            //}

        }

    #endregion

    #region GridView
    
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.mpSearch.Show();
        GridView1.PageIndex = e.NewPageIndex;
        ObjectDataSource1.Select();
    }

    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (vSelectMode == EnumSelectMode.SingleSelect)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //e.Row.Attributes.Add("onmouseover", "currentcolor=this.style.backgroundColor;this.style.backgroundColor= '#C0C0FF';this.style.cursor= 'hand';");
                //e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=currentcolor");
                e.Row.Attributes.Add("onClick", "javascript:__doPostBack('" + GridView1.ClientID + "','Select$" + e.Row.RowIndex + "');");
            }        
        }

    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.mpSearch.Show();

        if (vSelectMode == EnumSelectMode.SingleSelect)
        {

        }

    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        this.mpSearch.Show();

        if (ViewState["SortDirection"] == null)
        {
            ViewState["SortDirection"] = " ASC";
        }
        if (ViewState["SortExpression"] != null && ViewState["SortExpression"].ToString() == e.SortExpression)
        {
            if (ViewState["SortDirection"].ToString() == " DESC")
            {
                ViewState["SortDirection"] = " ASC";
            }
            else
            {
                ViewState["SortDirection"] = " DESC";
            }
        }
        else
        {
            ViewState["SortDirection"] = " ASC";
        }

        ViewState["SortExpression"] = e.SortExpression;

        ObjectDataSource1.Select();
    }



    #endregion

    #region ObjectDataSource1

        protected void ObjectDataSource1_Selected(object sender, ObjectDataSourceStatusEventArgs e)
    {
        if (GridView1.Columns.Count <=1)
        { 
            foreach (DataColumn objColumn in ((DataTable)e.ReturnValue).Columns)
            {

                if (objColumn.ColumnName == "GUID")
                {
                    //TemplateField TF = new TemplateField();
                    //TF.HeaderTemplate = new MyTemplate(DataControlRowType.Header, "");
                    //TF.ItemTemplate = new MyTemplate(DataControlRowType.DataRow, "GUID");
                    //TF.HeaderText = string.Empty;
                    //GridView1.Columns.Add(TF);
                }
                else
                { 
                    ListItem LI = new ListItem(this.GetLocalResourceObject(vTagName + "_" + objColumn.ColumnName).ToString(), objColumn.ColumnName);
                    ddlA.Items.Add(LI);

                    BoundField BF = new BoundField();
                    BF.HeaderText = LI.Text;
                    BF.DataField = LI.Value;
                    BF.SortExpression = LI.Value;
                    GridView1.Columns.Add(BF);

                }      
            }        
        }

        DataView dv = ((DataTable)e.ReturnValue).DefaultView;

        if (ViewState["SortExpression"] != null)
        {
            dv.Sort = ViewState["SortExpression"].ToString() + ViewState["SortDirection"].ToString();
        }

        dv.RowFilter = ObjectDataSource1.FilterExpression;

        GridView1.DataSource =dv ;
        GridView1.DataBind();

    }

    #endregion

    #region 其他控件事件
        protected void ddlA_Load(object sender, EventArgs e)
        {
            DropDownList ddlTMP = (DropDownList)sender;
            if (ddlTMP.Items.Count == 0)
            { 
                ListItem[] objItems = new ListItem[ddlA.Items.Count];
                ddlA.Items.CopyTo(objItems, 0);
                ((DropDownList)sender).Items.AddRange(objItems);         
            }

            ObjectDataSource1.FilterExpression += (" and " + ddlTMP.SelectedValue);
        }

        protected void ddlB_Load(object sender, EventArgs e)
        {
            DropDownList ddlTMP = (DropDownList)sender;
            if (((DropDownList)sender).Items.Count == 0)
            {
                ListItem[] objItems = new ListItem[ddlB.Items.Count];
                ddlB.Items.CopyTo(objItems, 0);
                ((DropDownList)sender).Items.AddRange(objItems);
            }

            ObjectDataSource1.FilterExpression += (" " + ddlTMP.SelectedValue);
        }

        protected void txtValue_Load(object sender, EventArgs e)
        {
            TextBox txtTMP = (TextBox)sender;
            if (ObjectDataSource1.FilterExpression.EndsWith("Like"))
            {
                ObjectDataSource1.FilterExpression += (" '%" + txtTMP.Text + "%'");
            }
            else
            {
                ObjectDataSource1.FilterExpression += (" '" + txtTMP.Text + "'");        
            }

        }		 
	#endregion

    #region ButtonClick
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            ObjectDataSource1.Select();
            this.mpSearch.Show();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            this.mpSearch.Show();
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            ObjectDataSource1.FilterExpression = string.Empty;
        }		 
	#endregion

    #region Method

        private void CreateTable(int RowCount)
    { 
        Table oTable = new Table();
        TableRow oRow;
        TableCell oCell;
        DropDownList ddlFieldName;
        DropDownList ddlCondition;
        TextBox txtValue;

        oTable.BorderWidth = 0;
        oTable.CellPadding = 0;
        oTable.CellSpacing = 0;
        PlaceHolder1.Controls.Add(oTable);
        
        for (int i = 1; i <= RowCount; i++)
        {        
            oRow = new TableRow();
            oTable.Rows.Add(oRow); 
            oCell =new TableCell();
            oRow.Cells.Add(oCell);
            ddlFieldName = new DropDownList();
            ddlFieldName.Load += ddlA_Load;
            oCell.Controls.Add(ddlFieldName); 
            oCell = new TableCell();
            oRow.Cells.Add(oCell);
            ddlCondition = new DropDownList();
            ddlCondition.Load += ddlB_Load;
            oCell.Controls.Add(ddlCondition);
            oCell = new TableCell();
            oRow.Cells.Add(oCell);
            txtValue = new TextBox();
            txtValue.MaxLength = 20;
            txtValue.Load += txtValue_Load;
            oCell.Controls.Add(txtValue);
        }    
    
    }

    #endregion

}

public partial class WebForm_CSharpCode_SelectControl : System.Web.UI.UserControl
{
    #region 給主頁面用的

        public delegate void OKClickDelegate(object sender, EventArgs e);
        public event OKClickDelegate OKButton_Click;

        public enum EnumSelectMode
        { 
            SingleSelect,MultiSelect 
        }

        #region Property

            public EnumSelectMode vSelectMode
            {
                get
                {
                    return ViewState["SelectMode"] == null ? EnumSelectMode.SingleSelect : (EnumSelectMode)ViewState["SelectMode"];
                }
                set
                {
                    ViewState["SelectMode"] = value;
                }
            }

            public string vTagName
            {
                get
                {
                    return ViewState["TagName"] == null ? string.Empty : ViewState["TagName"].ToString();
                }
                set
                {
                    ViewState["TagName"] = value;
                }
            }

            public System.Collections.Hashtable vWhereParams
            {
                get
                {
                    return (System.Collections.Hashtable)ViewState["WhereParams"];
                }
                set
                {
                    ViewState["WhereParams"] = value;
                }
            }

            public int PopUpWidth
            {
                set
                {
                    panel1.Width = value;
                }
            }  

            public List<string>  vSelectedValues
            {
                get
                {
                    List<string> listSelectedValues = new List<string>();

                    foreach (GridViewRow gvr in this.GridView1.Rows)
                    {
                        DataKey key = GridView1.DataKeys[gvr.RowIndex];
                        if (((CheckBox)gvr.FindControl("CheckBox1")).Checked == true)
                        {
                            listSelectedValues.Add(key["GUID"].ToString());
                        }

                    }

                    return listSelectedValues;
                }
                   
            }

        #endregion

        #region Method
            //按下OK確定
            protected void btnOK_Click(object sender, EventArgs e)
            {
                ObjectDataSource1.FilterExpression = string.Empty;

                if (OKButton_Click != null)
                {
                    OKButton_Click(this, e);
                }
            }

            //初始畫面及Show出來
            public void InitDataAndShow()
            {
                ObjectDataSource1.SelectParameters.Clear();
                AddWhereParams();
                ObjectDataSource1.Select();
                this.mpSearch.Show();
            }

            //幫ObjectDataSource加上Parameter
	        public void AddWhereParams()
            {
                System.Collections.Hashtable WhereParams = (System.Collections.Hashtable)vWhereParams;
                if(WhereParams!=null && WhereParams.Count>0)
                {
                    foreach (System.Collections.DictionaryEntry objWhereParam in WhereParams)
                    { 
                        ObjectDataSource1.SelectParameters.Add(new Parameter(objWhereParam.Key.ToString(),System.TypeCode.String,objWhereParam.Value.ToString()));            
                    }       
                
                }
            } 

	    #endregion



    #endregion

}

//public class MyTemplate:ITemplate 
//{
//    private DataControlRowType MyDataControlRowType;
//    private string MyColumnName;

//    public MyTemplate(DataControlRowType theDataControlRowType, string theColumnName)
//    {
//        MyDataControlRowType = theDataControlRowType;
//        MyColumnName = theColumnName;
//    }


//    #region ITemplate 成員

//    public void InstantiateIn(System.Web.UI.Control container)
//    {
//        switch (MyDataControlRowType)
//        {
//            case DataControlRowType.DataRow:
//                CheckBox chkSelect = new CheckBox();
//                chkSelect.ID = "chkSelect";
//                container.Controls.Add(chkSelect);
//                Literal lblGUIDaa = new Literal();
//                lblGUIDaa.Text = "dfregvreagreagra";
//                //lblGUIDaa.DataBinding +=new EventHandler(lblGUIDaa_DataBinding);
//                container.Controls.Add(lblGUIDaa);
//                break;
//            case DataControlRowType.EmptyDataRow:
//                break;
//            case DataControlRowType.Footer:
//                break;
//            case DataControlRowType.Header:
//                Label lblGUID = new Label();
//                lblGUID.Text ="123";
//                container.Controls.Add(lblGUID);
//                break;
//            case DataControlRowType.Pager:
//                break;
//            case DataControlRowType.Separator:
//                break;
//            default:
//                break;
//        }   

//    }

//    #endregion








//}